package com.huwaiwai.fork_join.demo01;

import lombok.AllArgsConstructor;

import java.util.concurrent.RecursiveTask;

/**
 * Created by huweiwei on 2017/4/14.
 */
@AllArgsConstructor
public class MyRecursiveTask extends RecursiveTask {
    private static final int THRESHOLD = 500000;
    private int start;
    private int end;
    @Override
    protected Object compute() {
        int sum = 0;
        boolean canCompute = (end - start) <= THRESHOLD;

        if (canCompute) {
            for (int i = start; i <= end; i++) {
                sum += i;
            }
        } else {
            int middle = (start + end) / 2;
            MyRecursiveTask leftTask = new MyRecursiveTask(start, middle);
            MyRecursiveTask rightTask = new MyRecursiveTask(middle + 1, end);
            leftTask.fork();
            rightTask.fork();
            int leftResult = (int) leftTask.join();
            int rightResult = (int) rightTask.join();
            sum = leftResult + rightResult;
        }
        return sum;
    }
}
